import {
  format,
  autoFixed
} from '../utils.js'
class Paint {
  constructor(args) {
    const {
      canvasId,
      timeId,
      canvasConfig
    } = args
    if (!canvasId || !timeId) {
      console.error('LveRecord: canvasId 和 timeId为必传项')
      return
    }
    this.canvas = canvasId // 画布dom
    this.context = canvasId.getContext('2d') // 画布对象
    this.canvasConfig = canvasConfig
    this.canvasHistory = [] // 历史栈
    this.time = 0 // 当前时间
    this.timer = null // 录制时间定时器
    this.timeDom = timeId // 时间展示dom
    this.lastTime = 0 // 上一次记录的时间
    this.timeStepUnit = 25 // 录制时间间隔
    this.initCanvas()
    this.initTime()
  }
  /**
   * 设置录制时间间隔（间隔越小绘制越精细，但是数据量也会越大）（单位毫秒）
   **/
  setTimeStep = (stepUnit) => {
    this.timeStepUnit = stepUnit
  }
  /**
   * 获取录制时间间隔（单位毫秒）
   **/
  getTimeStep = () => {
    return this.timeStepUnit
  }
  /**
   * 获取录制数据
   **/
  getData = () => {
    return this.canvasHistory
  }
  /**
   * 事件初始化
   **/
  initEvent = () => {
    this.canvas.addEventListener('mousedown', this.startAction);
  }
  /**
   * 开始录制
   **/
  startRecord = (stream) => {
    this.initEvent()
    this.timer = setInterval(() => {
      this.time += this.timeStepUnit / 1000
      this.timeDom.textContent = format(this.time)
    }, this.timeStepUnit)
  }
  /**
   * 暂停录制
   **/
  pauseRecord = () => {
    clearInterval(this.timer)
    this.timer = null
  }
  /**
   * 继续录制
   **/
  resumeRecord = () => {
    if (!this.timer) {
      this.timer = setInterval(() => {
        this.time += this.timeStepUnit / 1000
        this.timeDom.textContent = format(this.time)
      }, this.timeStepUnit)
    }
  }
  /**
   * 结束录制
   **/
  stopRecord = () => {
    this.canvasHistory.push({
      f: 'system',
      s: 'stop',
      t: autoFixed(this.time - this.lastTime, 3),
      ct: autoFixed(this.time, 3)
    })
    this.timer && clearInterval(this.timer)
    this.time = 0
    this.lastTime = 0
  };
  /**
   * 插入本地背景图片
   * @param type contain 保持宽高比例 | cover 全屏覆盖
   **/
  insertImage = (type = 'contain') => {
    if (!(type === 'contain' || type === 'cover')) {
      console.error('LveRecord: 插入图片尺寸错误');
      return;
    }
    const inputObj = document.createElement('input');
    // 不能改变this指向，并且要调用外部方法
    inputObj.addEventListener('change', this.readFile.bind(inputObj, this, type), false);
    inputObj.type = 'file';
    inputObj.accept = 'image/*';
    inputObj.click();
    this.pauseRecord()
  }
  /**
   * 解析本地图片并转化为base64
   * @param comp Paint类
   * @param type 图片尺寸大小
   **/
  readFile = function(comp, type) {
    const file = this.files[0]; // 获取input输入的图片
    if(!/image\/\w+/.test(file.type)){
        alert("请确保文件为图像类型");
        return false;
    } // 判断是否图片
    const reader = new FileReader();
    reader.readAsDataURL(file); // 转化成base64数据类型
    reader.onload = function(e){
      const img = new Image();
      img.src = this.result;
      img.onload = () => {
        const width = img.naturalWidth;
        const height = img.naturalHeight;
        const params = {
          width,
          height,
          type
        }
        comp.drawLocalImageToCanvas(this.result, params);
      }
    }
  }
  /**
   * 绘制本地图片到canvas上（画板区）
   * @param imgData 图像数据
   * @param imgConfig 图片相关
   **/
  drawLocalImageToCanvas = (imgData, imgConfig) => {
    const canvasImage = document.querySelector('#canvas-image');
    if (!canvasImage.classList.contains('old-movie')) {
      canvasImage.classList.add('old-movie');
    }
    canvasImage.style.backgroundImage = `url(${imgData})`;
    canvasImage.style.backgroundSize = imgConfig.type;
    canvasImage.style.backgroundRepeat = 'no-repeat';
    canvasImage.style.backgroundPosition = 'center center';
    this.canvasHistory.push({
      f: 'image',
      s: imgData,
      t: autoFixed(this.time - this.lastTime, 3),
      ct: autoFixed(this.time, 3),
      o: imgConfig
    });
    this.lastTime = this.time;
    if (this.time !== 0) {
      this.resumeRecord();
    }
  }
  /**
   * canvas涂鸦事件开始
   **/
  startAction = (e) => {
    this.context.strokeStyle = '#000';
    this.context.beginPath();
    this.context.moveTo(e.offsetX, e.offsetY);
    this.context.stroke();
    this.canvasHistory.push([{
      f: 'pen',
      s: 'start',
      x: e.offsetX,
      y: e.offsetY,
      t: autoFixed(this.time - this.lastTime, 3),
      ct: autoFixed(this.time, 3) // 当前时间
    }])
    this.lastTime = this.time

    this.canvas.addEventListener('mousemove', this.moveAction);
    this.canvas.addEventListener('mouseup', this.endAction);
  }
  /**
   * canvas涂鸦事件过程
   **/
  moveAction = (e) => {
    this.context.lineTo(e.offsetX, e.offsetY);
    this.context.stroke();
    this.canvasHistory[this.canvasHistory.length - 1].push({
      f: 'pen',
      s: 'ing',
      x: e.offsetX,
      y: e.offsetY,
      t: autoFixed(this.time - this.lastTime, 3), // 与上一个操作的时间间隔
      ct: autoFixed(this.time, 3) // 当前时间
    })
    this.lastTime = this.time
  }
  /**
   * canvas涂鸦事件结束
   **/
  endAction = (e) => {
    this.context.closePath();
    this.canvasHistory[this.canvasHistory.length - 1].push({
      f: 'pen',
      s: 'end',
      x: e.offsetX,
      y: e.offsetY,
      t: autoFixed(this.time - this.lastTime, 3),
      ct: autoFixed(this.time, 3) // 当前时间
    })
    this.lastTime = this.time
    this.canvas.removeEventListener('mousemove', this.moveAction);
    this.canvas.removeEventListener('mouseup', this.endAction);
  }
  /**
   * 初始化canvas
   **/
  initCanvas = () => {
    // 设置canvas宽高
    this.canvas.width = this.canvasConfig?.width ?? 800
    this.canvas.height = this.canvasConfig?.height ?? 400
    // 笔触样式
    this.context.lineWidth = this.canvasConfig?.lineWidth ?? 1
  }
  /**
   * 初始化时间
   **/
  initTime = () => {
    this.timeDom.textContent = format(this.time)
  }
}

export default Paint